import datetime
import logging
import time
import urllib
from urllib import request, parse
import ssl
import json
import playsound

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
f_handler = logging.FileHandler('trace2.log')
f_handler.setLevel(logging.INFO)
f_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s"))
logger.addHandler(f_handler)

context = ssl._create_unverified_context()

url = "https://maicai.api.ddxq.mobi/order/addNewOrder"
uid = "59786872dc759e40ec5a5e68"  # 用户号，从Fiddler中抓取
station_id = "6108f66781ff030001369967"  # 站点好，小程序首页中选中自家地址后，再从Fiddler抓取
cookie = "DDXQSESSID=7d436ca457008b1c829efe8ac176a26b"  # 登录后，从Fiddler抓取
# package_order = {"payment_order":{"reserved_time_start":1649723052,"reserved_time_end":1649730600,"price":"199.10","freight_discount_money":"5.00","freight_money":"5.00","order_freight":"0.00","parent_order_sign":"43fe20e810116d1f87139a681956c0b5","product_type":1,"address_id":"5eb951e9c7316f5e8b9e79c9","form_id":"e52768846a83465894d3a8530818cf5b","receipt_without_sku":"null","pay_type":6,"vip_money":"","vip_buy_user_ticket_id":"","coupons_money":"","coupons_id":""},"packages":[{"products":[{"id":"5e5ca3507cdbf01318697dd2","parent_id":"","count":1,"cart_id":"b0e00c2fbc01cfea8b5d191f32e53894","price":"57.90","product_type":0,"is_booking":0,"product_name":"鲜活多宝鱼1条 约450g","small_image":"https://imgnew.ddimg.mobi/product/9f4a9a1303e44ec7a26816379189291a.jpg?width=800&height=800","sale_batches":{"batch_type":-1},"order_sort":1,"sizes":[{"id":1,"title":"处理方式","name":"杀好（不要内脏）","price":"0.00","is_irreversible":1}]},{"id":"621598e99334c0cabbc562ec","parent_id":"","count":1,"cart_id":"621598e99334c0cabbc562ec","price":"6.90","product_type":0,"is_booking":0,"product_name":"绿色和美精选鸡翅尖 400g","small_image":"https://imgnew.ddimg.mobi/product/827ebd4b04c84fa897a146c1ba94860b.jpg?width=800&height=800","sale_batches":{"batch_type":-1},"order_sort":2,"sizes":[]},{"id":"604840a547987eb75d42291b","parent_id":"","count":1,"cart_id":"604840a547987eb75d42291b","price":"6.80","product_type":0,"is_booking":0,"product_name":"绿色和美精选鸡小胸 400g/袋","small_image":"https://img.ddimg.mobi/product/59427e1cfdd611615347922908.jpg?width=800&height=800","sale_batches":{"batch_type":-1},"order_sort":3,"sizes":[]},{"id":"622b0f2a876fbc49bebb8041","parent_id":"","count":1,"cart_id":"622b0f2a876fbc49bebb8041","price":"12.90","product_type":0,"is_booking":0,"product_name":"甜玉米 900g/份","small_image":"https://img.ddimg.mobi/product/88948b5b823d41556164221135.jpg!deliver.product.list","sale_batches":{"batch_type":-1},"order_sort":4,"sizes":[]},{"id":"61af31dda89a2c73b645f01a","parent_id":"","count":1,"cart_id":"61af31dda89a2c73b645f01a","price":"78.00","product_type":0,"is_booking":0,"product_name":"意大利进口律动之乐起泡葡萄酒 750ml/瓶","small_image":"https://imgnew.ddimg.mobi/product/cfb41a33e6e3422b91c057506ff92873.jpg?width=800&height=800","sale_batches":{"batch_type":-1},"order_sort":6,"sizes":[]},{"id":"5d40219710abf1329643a268","parent_id":"","count":1,"cart_id":"5d40219710abf1329643a268","price":"14.80","product_type":0,"is_booking":0,"product_name":"崇明芦笋 350g/份","small_image":"https://imgnew.ddimg.mobi/product/6479df37555e493b95eb790a978fcc23.jpg?width=800&height=800","sale_batches":{"batch_type":-1},"order_sort":9,"sizes":[]},{"id":"5da545e1b0055a0b4e3b1320","parent_id":"","count":1,"cart_id":"5da545e1b0055a0b4e3b1320","price":"9.90","product_type":0,"is_booking":0,"product_name":"崇明马兰头 300g/份","small_image":"https://img.ddimg.mobi/product/c68a1f0a703db1571112434232.jpg!deliver.product.list","sale_batches":{"batch_type":-1},"order_sort":11,"sizes":[]},{"id":"5e4a7d7810abf10ee56ad3bd","parent_id":"","count":1,"cart_id":"5e4a7d7810abf10ee56ad3bd","price":"11.90","product_type":0,"is_booking":0,"product_name":"胭脂红蜜薯 750g/袋","small_image":"https://img.ddimg.mobi/product/ba0e9c7545ccd1582775952322.jpg!deliver.product.list","sale_batches":{"batch_type":-1},"order_sort":13,"sizes":[]}],"total_money":"199.10","total_origin_money":"199.10","goods_real_money":"199.10","total_count":8,"cart_count":8,"is_presale":0,"instant_rebate_money":"0.00","used_balance_money":"0.00","can_used_balance_money":"0.00","used_point_num":0,"used_point_money":"0.00","can_used_point_num":0,"can_used_point_money":"0.00","is_share_station":0,"only_today_products":[],"only_tomorrow_products":[],"package_type":1,"package_id":1,"front_package_text":"即时配送","front_package_type":0,"front_package_stock_color":"#2FB157","front_package_bg_color":"#fbfefc","eta_trace_id":"","reserved_time_start":1649723052,"reserved_time_end":1649730600,"soon_arrival":"","first_selected_big_time":1}]}
# package_order = {"payment_order":{"reserved_time_start":1649723052,"reserved_time_end":1649730600,"price":"199.10","freight_discount_money":"5.00","freight_money":"5.00","order_freight":"0.00","parent_order_sign":"43fe20e810116d1f87139a681956c0b5","product_type":1,"address_id":"5eb951e9c7316f5e8b9e79c9","form_id":"e52768846a83465894d3a8530818cf5b","receipt_without_sku":"null","pay_type":6,"vip_money":"","vip_buy_user_ticket_id":"","coupons_money":"","coupons_id":""},"packages":[{"products":[{"id":"5e5ca3507cdbf01318697dd2","parent_id":"","count":1,"cart_id":"b0e00c2fbc01cfea8b5d191f32e53894","price":"57.90","product_type":0,"is_booking":0,"product_name":"鲜活多宝鱼1条 约450g","small_image":"https://imgnew.ddimg.mobi/product/9f4a9a1303e44ec7a26816379189291a.jpg?width=800&height=800","sale_batches":{"batch_type":-1},"order_sort":1,"sizes":[{"id":1,"title":"处理方式","name":"杀好（不要内脏）","price":"0.00","is_irreversible":1}]},{"id":"621598e99334c0cabbc562ec","parent_id":"","count":1,"cart_id":"621598e99334c0cabbc562ec","price":"6.90","product_type":0,"is_booking":0,"product_name":"绿色和美精选鸡翅尖 400g","small_image":"https://imgnew.ddimg.mobi/product/827ebd4b04c84fa897a146c1ba94860b.jpg?width=800&height=800","sale_batches":{"batch_type":-1},"order_sort":2,"sizes":[]},{"id":"604840a547987eb75d42291b","parent_id":"","count":1,"cart_id":"604840a547987eb75d42291b","price":"6.80","product_type":0,"is_booking":0,"product_name":"绿色和美精选鸡小胸 400g/袋","small_image":"https://img.ddimg.mobi/product/59427e1cfdd611615347922908.jpg?width=800&height=800","sale_batches":{"batch_type":-1},"order_sort":3,"sizes":[]},{"id":"622b0f2a876fbc49bebb8041","parent_id":"","count":1,"cart_id":"622b0f2a876fbc49bebb8041","price":"12.90","product_type":0,"is_booking":0,"product_name":"甜玉米 900g/份","small_image":"https://img.ddimg.mobi/product/88948b5b823d41556164221135.jpg!deliver.product.list","sale_batches":{"batch_type":-1},"order_sort":4,"sizes":[]},{"id":"61af31dda89a2c73b645f01a","parent_id":"","count":1,"cart_id":"61af31dda89a2c73b645f01a","price":"78.00","product_type":0,"is_booking":0,"product_name":"意大利进口律动之乐起泡葡萄酒 750ml/瓶","small_image":"https://imgnew.ddimg.mobi/product/cfb41a33e6e3422b91c057506ff92873.jpg?width=800&height=800","sale_batches":{"batch_type":-1},"order_sort":6,"sizes":[]},{"id":"5d40219710abf1329643a268","parent_id":"","count":1,"cart_id":"5d40219710abf1329643a268","price":"14.80","product_type":0,"is_booking":0,"product_name":"崇明芦笋 350g/份","small_image":"https://imgnew.ddimg.mobi/product/6479df37555e493b95eb790a978fcc23.jpg?width=800&height=800","sale_batches":{"batch_type":-1},"order_sort":9,"sizes":[]},{"id":"5da545e1b0055a0b4e3b1320","parent_id":"","count":1,"cart_id":"5da545e1b0055a0b4e3b1320","price":"9.90","product_type":0,"is_booking":0,"product_name":"崇明马兰头 300g/份","small_image":"https://img.ddimg.mobi/product/c68a1f0a703db1571112434232.jpg!deliver.product.list","sale_batches":{"batch_type":-1},"order_sort":11,"sizes":[]},{"id":"5e4a7d7810abf10ee56ad3bd","parent_id":"","count":1,"cart_id":"5e4a7d7810abf10ee56ad3bd","price":"11.90","product_type":0,"is_booking":0,"product_name":"胭脂红蜜薯 750g/袋","small_image":"https://img.ddimg.mobi/product/ba0e9c7545ccd1582775952322.jpg!deliver.product.list","sale_batches":{"batch_type":-1},"order_sort":13,"sizes":[]}],"total_money":"199.10","total_origin_money":"199.10","goods_real_money":"199.10","total_count":8,"cart_count":8,"is_presale":0,"instant_rebate_money":"0.00","used_balance_money":"0.00","can_used_balance_money":"0.00","used_point_num":0,"used_point_money":"0.00","can_used_point_num":0,"can_used_point_money":"0.00","is_share_station":0,"only_today_products":[],"only_tomorrow_products":[],"package_type":1,"package_id":1,"front_package_text":"即时配送","front_package_type":0,"front_package_stock_color":"#2FB157","front_package_bg_color":"#fbfefc","eta_trace_id":"","reserved_time_start":1649723052,"reserved_time_end":1649730600,"soon_arrival":"","first_selected_big_time":1}]}
package_order = {"payment_order":{"reserved_time_start":1649724976,"reserved_time_end":1649730600,"price":"10.90","freight_discount_money":"5.00","freight_money":"5.00","order_freight":"0.00","parent_order_sign":"69d72da6de6b12f1823ca7369cfa60a0","product_type":1,"address_id":"5eb951e9c7316f5e8b9e79c9","form_id":"f043c58b862348f78e32316e9cabb57e","receipt_without_sku":"","pay_type":6,"vip_money":"","vip_buy_user_ticket_id":"","coupons_money":"","coupons_id":""},"packages":[{"products":[{"id":"5d36b90010abf132987a16d9","parent_id":"","count":1,"cart_id":"5d36b90010abf132987a16d9","price":"10.90","product_type":0,"is_booking":0,"product_name":"崇明番茄 450g/份","small_image":"https://img.ddimg.mobi/product/de6315ed01c9c1608892597596.jpg?width=800&height=800","sale_batches":{"batch_type":-1},"order_sort":1,"sizes":[]}],"total_money":"10.90","total_origin_money":"10.90","goods_real_money":"10.90","total_count":1,"cart_count":1,"is_presale":0,"instant_rebate_money":"0.00","used_balance_money":"0.00","can_used_balance_money":"0.00","used_point_num":0,"used_point_money":"0.00","can_used_point_num":0,"can_used_point_money":"0.00","is_share_station":0,"only_today_products":[],"only_tomorrow_products":[],"package_type":1,"package_id":1,"front_package_text":"即时配送","front_package_type":0,"front_package_stock_color":"#2FB157","front_package_bg_color":"#fbfefc","feReservedTimeStr":"","eta_trace_id":"","reserved_time_start":1649724976,"reserved_time_end":1649730600,"soon_arrival":"","first_selected_big_time":1}]}


postDict = {
    "uid": uid,
    "longitude": "121.425446",
    "latitude": "31.237419",
    "station_id": station_id,
    "city_number": "0101",
    "api_version": "9.49.2",
    "app_version": "2.82.0",
    "applet_source": "",
    "channel": "applet",
    "app_client_id": "4",
    "sharer_uid": "",
    "s_id": "7d436ca457008b1c829efe8ac176a26b",
    "openid": "osP8I0WwHO78fDdWv6vaJWMVXZFg",
    "h5_source": "",
    "device_token": "WHJMrwNw1k/FKPjcOOgRd+J1ee6rW3n/PRrH6Kq8m9g66TlQ+UvE66AmDe51vPg9Mc/XtPI0QeUz7MbJchBByraRk0jv7nINFdCW1tldyDzmauSxIJm5Txg==1487582755342",
    "package_order": package_order,
    "showMsg": False,
    "showData": True,
    "ab_config": {"key_onion": "C"},
    "nars": "af84c8323cf7ba0d5c8546b2fda00fca",
    "sesi": "Qv3uCdZ0ca21b9289c09eefceaf7db9abe60a2e"
}
headers = {
    "Host": "maicai.api.ddxq.mobi",
    "content-type": "application/x-www-form-urlencoded",
    # "Connection": "keep-alive",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat",
    "ddmc-api-version": "9.49.2",
    "ddmc-app-client-id": "4",
    "ddmc-build-version": "2.82.0",
    "ddmc-channel": "applet",
    "ddmc-city-number": "0101",
    "ddmc-device-id": "osP8I0WwHO78fDdWv6vaJWMVXZFg",
    "ddmc-ip": "",
    "ddmc-latitude": "31.237419",
    "ddmc-longitude": "121.425446",
    "ddmc-os-version": "[object Undefined]",
    "ddmc-station-id": station_id,
    "ddmc-uid": uid,
    "Referer": "https://servicewechat.com/wx1e113254eda17715/422/page-frame.html",
    # "Accept-Encoding": "gzip, deflate, br",
    "Cookie": cookie
}
request = urllib.request.Request(url=url, headers=headers)
data_string = urllib.parse.urlencode(postDict)
last_data = bytes(data_string, encoding='utf-8')
print("started")
while True:
    now = datetime.datetime.now()
    now_time = datetime.datetime.strptime(now.strftime('%H:%M:%S'), '%H:%M:%S')
    open_time = datetime.datetime.strptime('6:20:00', '%H:%M:%S')
    close_time = datetime.datetime.strptime('22:00:00', '%H:%M:%S')
    # current_time = time.localtime(time.time())
    # if ((current_time.tm_hour >= 5) and (current_time.tm_min >= 59) and (current_time.tm_sec >= 57)):
    # if current_time.tm_hour >= 5:
    if open_time < now_time < close_time:
        print("\n进入抢单时间！！！冲鸭！！！")
        try:
            # 下单前检查运力时间匹配
            reserved_time_start = package_order["payment_order"]["reserved_time_start"]
            if int(time.time()) > int(reserved_time_start):
                raise Exception(f"超出选择的配送时间啦，重新选择配送时间！！！")

            response = urllib.request.urlopen(request, data=last_data)
            json_resp = json.loads(response.read().decode("utf-8"))
            logger.info(json_resp)
            if "success" in json_resp and not json_resp["success"]:
                print(f"errorCode={json_resp['code']}, msg={json_resp['msg']}")
            else:
                print("下单成功啦！！！")
                playsound.playsound("alert1.mp3")
        except Exception as ex:
            print("error found...")
            print(ex)
            logger.error(ex)
        time.sleep(1)
    else:
        print(".", end="", flush=True)
        time.sleep(1)